import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MessageBox;
import org.w3c.dom.Document;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class XMLUtil {
	public static Document readXML(String filename) {
		Document document = null;
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setIgnoringElementContentWhitespace(true);
		factory.setIgnoringComments(true);
		factory.setValidating(false);
		DocumentBuilder builder;
		try {
			builder = factory.newDocumentBuilder();
			builder.setErrorHandler(new MyErrorHandler());
			document = builder.parse(filename);
			return document;
		} catch (Exception e) {
			return null;
		}
		// } catch (ParserConfigurationException e1) {
		// // TODO Auto-generated catch block
		// e1.printStackTrace();
		// } catch (SAXException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// } catch (IOException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
	}

	private static class MyErrorHandler implements ErrorHandler {
		public void warning(SAXParseException e) throws SAXException {
			System.out.println("Warning: ");
			printInfo(e);
		}

		public void error(SAXParseException e) throws SAXException {
			System.out.println("Error: ");
			printInfo(e);
		}

		public void fatalError(SAXParseException e) throws SAXException {
			System.out.println("Fattal error: ");
			printInfo(e);
		}

		private void printInfo(SAXParseException e) {
			System.out.println("   Public ID: " + e.getPublicId());
			System.out.println("   System ID: " + e.getSystemId());
			System.out.println("   Line number: " + e.getLineNumber());
			System.out.println("   Column number: " + e.getColumnNumber());
			System.out.println("   Message: " + e.getMessage());
			messageOK("   Public ID: " + e.getPublicId() + "\n"
					+ "   System ID: " + e.getSystemId() + "\n"
					+ "   Line number: " + e.getLineNumber() + "\n"
					+ "   Column number: " + e.getColumnNumber()
					+ "   Message: " + e.getMessage());
		}
	}

	public static void messageOK(String strContent) {
		MessageBox messageBox = new MessageBox(null, SWT.OK);
		messageBox.setText("Information");
		messageBox.setMessage(strContent);
		messageBox.open();
	}

	public static String getData(Object obj, String val) {
		return (obj == null) ? val : obj.toString();
	}
}
